<!--
 * @FileDescription: 新增/修改 设备弹窗
 * @Author: 祝小文
 * @Date: 2022-10-08 09:15
 -->
<script setup lang="ts">
import { ElMessage } from 'element-plus'
import { emitter } from '@/composables'
import Title from '@/components/title/index.vue'
import DialogPopUp from '@/components/DialogPopUp/index.vue'
import sb_icon from '@/assets/image/mapIcon/sb-icon.png'
import { checkNumberTypeAndLength } from '@/utils/common'
import { queryZdZdmcInfo, querySBXXInfo, insertOrUpdateSBXX } from '@/service/api'

const chemicalStore = useChemicalStore()
const device = chemicalStore.productionStorage.device

const props = defineProps({
  cjInfo: {
    type: Object,
    default: () => {
      return {}
    },
  }, //采集信息,
})

//字典
const ywBool: any = chemicalStore.commonDictionaries.ywBool
const syzt: any = chemicalStore.commonDictionaries.syzt
const zdsblx: any = device.dictionaries.zdsblx

//字段默认值
function fieldDefault() {
  if (props.cjInfo.lx === 'edit') {
    const selectField = ['syzt', 'zdsblx']
    for (const key in sbInfo.value) {
      if (selectField.includes(key) && sbInfo.value[key] === '0') {
        if (key === 'syzt') {
          sbInfo.value.syzt = syzt[0].zddm
        } else if (key === 'zdsblx') {
          sbInfo.value.zdsblx = zdsblx[0].zddm
        }
      }
    }
  } else {
    sbInfo.value.syzt = syzt[0].zddm
    sbInfo.value.zdsblx = zdsblx[0].zddm

    const ywBool: any = ['ywbwc']
    for (const key in sbInfo.value) {
      if (ywBool.includes(key)) {
        sbInfo.value[key] = '0'
      }
    }
  }
}

//获取企业id
const qyId = computed(() => {
  return chemicalStore.qyInfo.id
})

//设备信息
const sbInfo = ref({
  sbmc: '',
  sbwh: '',
  syzt: '',
  sbzj: '',
  sbg: '',
  sbcz: '',
  zdsblx: '',
  ywbwc: '',
  sjrl: '',
  sjwd: '',
  sjyl: '',
  gzwdsx: '',
  gzylsx: '',
  bz: '',
})
//必填字段
const requiredNameArr = [
  'sbmc',
  'sbwh',
  'syzt',
  'sbzj',
  'sbg',
  'sbcz',
  'zdsblx',
  'ywbwc',
  'sjrl',
  'sjwd',
  'sjyl',
  'gzwdsx',
  'gzylsx',
]
//主要危险介质
const zywxjzList = ref([{ name: '', state: false }])

/** 表格 保存事件 */
const tableSaveClick = (item: any, index: any) => {
  if (!item.name) {
    return ElMessage.warning('请填写名称')
  }
  item.state = true
  //如果保存的数据是最后一项才需要添加新的一行
  if (zywxjzList.value.length === index + 1) {
    zywxjzList.value.push({ name: '', state: false })
  }
}

/** 表格 修改事件 */
const tableEditClick = (item: any) => {
  item.state = false
}

/** 表格 删除事件 */
const tableDeleteClick = (index: any) => {
  zywxjzList.value.splice(index, 1)
}

/** 渲染设备信息 */
function loadEquipmentInfo() {
  querySBXXInfo({ key: props.cjInfo.cjId }).then((res: any) => {
    delete res.id //过滤id
    delete res.cjsj //过滤创建时间
    delete res.gxsj //过滤更新时间

    //表格数据赋值
    if (res.zywxjz) {
      zywxjzList.value = []
      res.zywxjz.split('&^').forEach((item: any) => {
        zywxjzList.value.push({ name: item, state: true })
      })
      zywxjzList.value.push({ name: '', state: false })
      delete res.zywxjz
    }

    sbInfo.value = res

    fieldDefault() //字段默认值
  })
}

/** 取消点击事件 */
const cancelClick = () => {
  chemicalStore.closeAllPSDialog() //关闭全部弹窗
  device.addEquipmentShow = false
}

/** 重置点击事件 */
const resetClick = () => {
  sbInfo.value = {
    sbmc: '',
    sbwh: '',
    syzt: '',
    sbzj: '',
    sbg: '',
    sbcz: '',
    zdsblx: '',
    ywbwc: '',
    sjrl: '',
    sjwd: '',
    sjyl: '',
    gzwdsx: '',
    gzylsx: '',
    bz: '',
  }

  //下拉框默认值
  sbInfo.value.syzt = syzt[0].zddm
  sbInfo.value.zdsblx = zdsblx[0].zddm

  const ywBool: any = ['ywbwc']
  for (const key in sbInfo.value) {
    if (ywBool.includes(key)) {
      sbInfo.value[key] = '0'
    }
  }

  zywxjzList.value[zywxjzList.value.length - 1].name = ''
}

/** 保存点击事件 */
const saveClick = () => {
  /** 校验数据非空 Start */
  // let flag = false
  // //基本信息
  // for (const key in sbInfo.value) {
  //   if (requiredNameArr.includes(key) && !sbInfo.value[key]) {
  //     console.log(key, '字段未填写')
  //     flag = true
  //   }
  // }
  // if (flag) {
  //   return (chemicalStore.FormCheckConfirmShow = true)
  // }
  /** 校验数据非空 End */

  /** 校验数据类型和长度 Strat */
  if (!checkNumberTypeAndLength(sbInfo.value.sbzj, '设备直径', 6)) {
    return
  } else if (!checkNumberTypeAndLength(sbInfo.value.sbg, '设备高', 6)) {
    return
  } else if (!checkNumberTypeAndLength(sbInfo.value.sjrl, '设计容量', 8)) {
    return
  } else if (!checkNumberTypeAndLength(sbInfo.value.sjwd, '设计温度', 6)) {
    return
  } else if (!checkNumberTypeAndLength(sbInfo.value.sjyl, '设计压力', 6)) {
    return
  } else if (!checkNumberTypeAndLength(sbInfo.value.gzwdsx, '工作温度上限', 6)) {
    return
  } else if (!checkNumberTypeAndLength(sbInfo.value.gzylsx, '工作压力上限', 6)) {
    return
  }
  /** 校验数据类型和长度 End */

  device.addEquipmentShow = false

  //过滤为空的数据 拼接为字符串
  let zywxjz = ''
  zywxjzList.value.forEach((item: any) => {
    if (item.name && item.state) {
      zywxjz += `${item.name}&^`
    }
  })
  //截取掉最后的&^符号
  zywxjz = zywxjz.substring(0, zywxjz.lastIndexOf('&^'))

  const params: any = {
    ...sbInfo.value,
    zywxjz,
    qyid: qyId.value,
    sfyx: 1,
  }

  //判断该设备属于装置还是设备
  if (props.cjInfo.fidType === 'zz') {
    params.zzqid = props.cjInfo.fid
  } else if (props.cjInfo.fidType === 'dy') {
    params.dyid = props.cjInfo.fid
  }

  //如果是修改需要传cjid
  if (props.cjInfo.lx === 'edit') {
    params.id = props.cjInfo.cjId
  }

  insertOrUpdateSBXX(params)
    .then((res: any) => {
      emitter.emit('tabLeft_refreshData') //更新左侧tab统计数量

      //添加
      if (props.cjInfo.lx === 'add') {
        ElMessage.success('新增设备成功')
      }
      //修改
      else if (props.cjInfo.lx === 'edit') {
        ElMessage.success('修改设备成功')
        //需要修改地图要素的标注名称
        //如果已经标注过，需要修改dom
        window.GOverlayArray.forEach((item: any) => {
          if (item.name === props.cjInfo.cjId) {
            const el = document.createElement('div')
            el.className = 'maplabelpopup-one'
            // 标牌禁止右击
            el.setAttribute('oncontextmenu', 'return false')
            const img = document.createElement('img')
            img.src = sb_icon
            const div = document.createElement('div')
            div.innerText = `${sbInfo.value.sbwh} ${sbInfo.value.sbmc}`
            el.appendChild(img)
            el.appendChild(div)

            item.overlay.updateDom(el)
          }
        })
      }
      //刷新数据
      emitter.emit('zz_refreshData')
    })
    .catch((err: any) => {
      if (props.cjInfo.lx === 'add') {
        ElMessage.error('新增设备失败')
      } else if (props.cjInfo.lx === 'edit') {
        ElMessage.error('修改设备失败')
      }
    })
}

/** 如果是修改，需要重新渲染数据 */
watch(
  () => props.cjInfo.cjId,
  (newValue, oldValue) => {
    if (props.cjInfo.lx === 'edit') {
      loadEquipmentInfo()
    } else {
      resetClick() //重置表单
      fieldDefault() //字段默认值
    }
  },
  {
    immediate: true,
    deep: true,
  }
)
</script>

<template>
  <DialogPopUp
    title="设备信息"
    @cancel-click="cancelClick"
    @reset-click="resetClick"
    @save-click="saveClick"
  >
    <!-- 表单 -->
    <div>
      <!-- 装置基本信息 -->
      <div>
        <Title title-info="基本信息" />
        <el-form label-width="110px">
          <el-row>
            <el-col :span="24">
              <el-form-item label="设备名称">
                <el-input v-model="sbInfo.sbmc" />
              </el-form-item>
            </el-col>
          </el-row>

          <el-row :gutter="30">
            <el-col :span="12">
              <el-form-item label="设备位号">
                <el-input v-model="sbInfo.sbwh" />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="使用状态">
                <el-select v-model="sbInfo.syzt" placeholder="请选择">
                  <el-option
                    v-for="item in syzt"
                    :key="item.zddm"
                    :label="item.zdmc"
                    :value="item.zddm"
                  >
                  </el-option>
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>

          <el-row :gutter="30">
            <el-col :span="12">
              <el-form-item label="设备直径">
                <el-input v-model="sbInfo.sbzj">
                  <template #suffix>
                    <i>m</i>
                  </template>
                </el-input>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="设备高">
                <el-input v-model="sbInfo.sbg">
                  <template #suffix>
                    <i>m</i>
                  </template>
                </el-input>
              </el-form-item>
            </el-col>
          </el-row>

          <el-row :gutter="30">
            <el-col :span="12">
              <el-form-item label="设备材质">
                <el-input v-model="sbInfo.sbcz" />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="设备类型">
                <el-select v-model="sbInfo.zdsblx" placeholder="请选择">
                  <el-option
                    v-for="item in zdsblx"
                    :key="item.zddm"
                    :label="item.zdmc"
                    :value="item.zddm"
                  >
                  </el-option>
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>

          <el-row :gutter="30">
            <el-col :span="12">
              <el-form-item label="有无保温层">
                <el-select v-model="sbInfo.ywbwc" placeholder="请选择">
                  <el-option
                    v-for="item in ywBool"
                    :key="item.zddm"
                    :label="item.zdmc"
                    :value="item.zddm"
                  >
                  </el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="设计容量">
                <el-input v-model="sbInfo.sjrl">
                  <template #suffix>
                    <i>m³</i>
                  </template>
                </el-input>
              </el-form-item>
            </el-col>
          </el-row>

          <el-row :gutter="30">
            <el-col :span="12">
              <el-form-item label="设计温度">
                <el-input v-model="sbInfo.sjwd">
                  <template #suffix>
                    <i>℃</i>
                  </template>
                </el-input>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="设计压力">
                <el-input v-model="sbInfo.sjyl">
                  <template #suffix>
                    <i>MPa</i>
                  </template>
                </el-input>
              </el-form-item>
            </el-col>
          </el-row>

          <el-row :gutter="30">
            <el-col :span="12">
              <el-form-item label="工作温度上限">
                <el-input v-model="sbInfo.gzwdsx">
                  <template #suffix>
                    <i>℃</i>
                  </template>
                </el-input>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="工作压力上限">
                <el-input v-model="sbInfo.gzylsx">
                  <template #suffix>
                    <i>MPa</i>
                  </template>
                </el-input>
              </el-form-item>
            </el-col>
          </el-row>

          <el-row>
            <el-col :span="24">
              <el-form-item label="备注" prop="bz">
                <el-input v-model="sbInfo.bz" />
              </el-form-item>
            </el-col>
          </el-row>

          <!-- 主要危险介质 -->
          <div class="table-title">
            <div></div>
            <div>主要危险介质</div>
            <div></div>
          </div>
          <div class="zywxjz table-container">
            <div class="table-top-th">
              <div>序号</div>
              <div>名称</div>
              <div>操作</div>
            </div>
            <div class="table-content">
              <div v-for="(item, index) in zywxjzList" :key="index" class="table-item">
                <div>{{ index + 1 }}</div>
                <div>
                  <el-input
                    v-if="!item.state"
                    v-model="item.name"
                    style="width: 80%"
                    size="small"
                  />
                  <span
                    v-else
                    style="display: inline-block; width: 380px"
                    class="single-line-text-exceeds"
                    :title="item.name"
                    >{{ item.name }}</span
                  >
                </div>
                <div>
                  <div v-if="!item.state">
                    <img
                      src="@/assets/image/fire/保存.png"
                      style="cursor: pointer"
                      @click="tableSaveClick(item, index)"
                    />
                  </div>
                  <div v-else>
                    <img
                      style="cursor: pointer; margin-right: 10px"
                      src="@/assets/image/fire/编辑.png"
                      @click="tableEditClick(item)"
                    />
                    <img
                      style="cursor: pointer"
                      src="@/assets/image/fire/删除.png"
                      @click="tableDeleteClick(index)"
                    />
                  </div>
                </div>
              </div>
            </div>
          </div>
        </el-form>
      </div>
    </div>
  </DialogPopUp>
</template>

<style lang="less" scoped>
.table-title {
  position: relative;
  top: 10px;
  display: flex;
  align-items: center;
  color: #fff;
  font-size: 16px;
  div:first-child,
  div:last-child {
    flex: 1;
    height: 3px;
    background-color: #666;
  }
  div:nth-child(2) {
    display: flex;
    justify-content: center;
    align-items: center;
    width: 140px;
    text-align: center;
  }
}
.table-container {
  color: #fff;
  font-size: 16px;
  border: 1px solid #666;
  border-top: 0;
  .table-top-th {
    display: flex;
    padding-top: 18px;
    border-bottom: 1px solid #666;
    & > div {
      text-align: center;
    }
    div:nth-child(1) {
      width: 120px;
    }
    div:nth-child(2) {
      flex: 1;
    }
    div:nth-child(3) {
      width: 120px;
    }
  }
  .table-content {
    height: 200px;
    overflow: auto;
    .table-item {
      display: flex;
      align-items: center;
      height: 40px;
      border-bottom: 1px solid #666;
      & > div {
        text-align: center;
      }
      div:nth-child(1) {
        width: 120px;
      }
      div:nth-child(2) {
        flex: 1;
      }
      div:nth-child(3) {
        width: 120px;
      }
    }
  }
}
</style>
